package ch.bfh.mobicomp.soda2.barometer;

import java.io.Serializable;

import android.app.Service;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.util.Log;

public class BarometerListener implements SensorEventListener, Serializable {


	public static final float THRESHOLD = (float) 0.01;
	public static final short AMOUNT_OF_CHANGES_FOR_SIGNAL = 1;
	public static final short MAX_MEASURES = 10;
	private float lastValue = (float)0;
	private boolean changeDetected = false;
	private static final long serialVersionUID = 1L;
	public static final String KEY_BAROMETER_CHANGED = "Barometer has changed";
	public static final String KEY_BAROMETER_VALUE = "Barometer value";
	private SharedPreferences preferences;
	
	
	public BarometerListener(Service service) {
		
		preferences = service.getSharedPreferences("Barometer", Context.MODE_PRIVATE);
		
		Log.d(MainActivity.LOG_TAG, "Listener Konsturktor");
	}
	
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onSensorChanged(SensorEvent event) {

		Log.d(MainActivity.LOG_TAG, "Listener SensorEvent");
		
		changeDetected = Math.abs(lastValue-event.values[0]) > THRESHOLD;
		
		if (changeDetected)
			lastValue = event.values[0];
		
		Log.d(MainActivity.LOG_TAG, String.valueOf(event.values[0]));
		
		if (getBoolean() != changeDetected)
			setRecord(changeDetected);
		
		if (changeDetected)
			setRecord(event.values[0]);
		
		Log.d(MainActivity.LOG_TAG, "Barometerstatus " + changeDetected);		
	}
	
	public void setRecord(boolean hasChanged)
	{
		Editor editor=preferences.edit();
		editor.putBoolean(KEY_BAROMETER_CHANGED, hasChanged);
		editor.commit();
		Log.d(MainActivity.LOG_TAG, "setRecord Boolean");
	}
	
	public boolean getBoolean()
	{
		return preferences.getBoolean(KEY_BAROMETER_CHANGED, false);
	}
	
	public void setRecord(float value) {
		Editor editor=preferences.edit();
		editor.putFloat(KEY_BAROMETER_VALUE, value);
		editor.commit();
		Log.d(MainActivity.LOG_TAG, "setRecord Float");
	}
	
	public float getFloat()
	{
		return preferences.getFloat(KEY_BAROMETER_VALUE, 0);
	}

}
